package com.vitaf.cash.app.ui.activity

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import com.vitaf.cash.app.R
import com.vitaf.cash.app.common.VitafComAct
import com.vitaf.cash.app.databinding.VitafActApplyWaitBinding
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.utils.helper.VitafProcessHp
import com.vitaf.cash.lib.adapter.VitafOnSingleClickListener

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/25 18:45
 * @Annotation：SMS 等待
 */
class VitafApplyWaitAct: VitafComAct() {
    lateinit var binding: VitafActApplyWaitBinding
    //等待时长
    private var countdown = 10
    private var countdownTimer: MyCountDownTimer? = null

    override fun createVitafContentView(): View {
        binding = VitafActApplyWaitBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeVitafViews() {
        getTitleBarManager().setRootBackgroundColor(getColor(R.color.white))
        getTitleBarManager().setVisibility(View.VISIBLE)
        getTitleBarManager().setTitleVisibility(View.GONE)
        getTitleBarManager().setBackButtonVisibility(View.INVISIBLE)
        getTitleBarManager().setRightButtonIcon(R.mipmap.gombe_credit_image_customer_black_icon)

        val showKey = getString(R.string.gombe_credit_apply_wait_desc_key)
        val showText = String.format(getString(R.string.gombe_credit_apply_wait_desc_value),showKey)
        val startIndex = showText.indexOf(showKey)
        val spannable = SpannableString(showText)
        spannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FFFF4D3E)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        spannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textApplyWaitTips.text = spannable
    }

    override fun setupVitafEventListeners() {
        //联系客服
        setRightButtonClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("SMS Preview Page")
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,"SMS Preview Page")
            }
        })
    }

    override fun loadVitafData() {
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: VitafApplyWaitAct, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showUploadSmsDataTipsText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showUploadSmsDataComplete()
        }
    }

    /**
     * 设置文本
     */
    @SuppressLint("SetTextI18n")
    private fun showUploadSmsDataTipsText(){
        binding.textCountdown.text = "$countdown"
        showApplySmsDataStepStatusView()
    }

    /**
     * 倒计时完成
     */
    private fun showUploadSmsDataComplete(){
        showVitafLoading()
        //上报所有设备数据
        publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_SYC_ALL_DEVICE))
        //刷新主流程
        publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
    }

    /**
     *旋转动画
     */
    private fun getApplySmsDataAnimation(): Animation {
        // 创建一个旋转动画对象，从当前的角度旋转到指定的角度，持续时间为1000毫秒
        val rotateAnimation = RotateAnimation(0F, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        rotateAnimation.setDuration(1000L) // 设置动画持续时间
//        rotateAnimation.fillAfter = false // 动画执行完后保持结束状态
        rotateAnimation.isFillEnabled = true;
        rotateAnimation.fillBefore = false;
        rotateAnimation.setRepeatCount(Animation.INFINITE); // 设置动画重复次数
        return rotateAnimation
    }

    /**
     * 显示状态
     */
    private fun showApplySmsDataStepStatusView(){
        if (countdown > 6){
            binding.imgWaitStep1.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_progress_icon)
            binding.imgWaitStep2.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_progress_icon)
            binding.imgWaitStep3.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_progress_icon)
            return
        }

        if (countdown > 3){
            binding.imgWaitStep1.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_completed_icon)
            binding.imgWaitStep2.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_progress_icon)
            binding.imgWaitStep3.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_progress_icon)
            return
        }
        binding.imgWaitStep1.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_completed_icon)
        binding.imgWaitStep2.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_completed_icon)

        if (countdown >= 1){
            binding.imgWaitStep3.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_progress_icon)
            return
        }
        binding.imgWaitStep3.setImageResource(R.mipmap.gombe_credit_image_apply_wait_step_completed_icon)
    }

    override fun onVitafPublishEvent(event: VitafEventData) {
        super.onVitafPublishEvent(event)
        when(event.eventType){
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> {
                hideVitafLoading()
                //需要校验 WhatsApp 或 SMS
                if (VitafProcessHp.isGombeCreditCheckWhatsApp() || VitafProcessHp.isGombeCreditCheckSMS()){
//                    CheckAct.start(this)
                } else {
//                    val pName = getProductName()
//                    val pToken = getProductToken()
//                    ActivityOrderDetails.start(this, pName, pToken)
                }
                finish()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_SMS_PREVIEW_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_SMS_PREVIEW_END)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}